package com.example.dell.newstart.my;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.dell.newstart.R;
import com.example.dell.newstart.base.BaseActivity;
import com.example.dell.newstart.bean.MyApp;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;


public class MyInformationActivity extends BaseActivity implements View.OnClickListener {
    private ImageView mReturnView;
    private ImageView mImageView;
    private ImageView goToNicheng;
    private ImageView goToPhone;
    private ImageView goToEmail;
    private ImageView goToSex;
    private ImageView goToBirthday;
    private TextView ivSex;
    private AlertDialog alertDialog1;
    //private AlertDialog alertDialog2;
    private static final int TAKE_PHOTO = 11;// 拍照
    private static final int CROP_PHOTO = 12;// 裁剪图片
    private static final int LOCAL_CROP = 13;// 本地图库

    private Button btn_choose_picture;
    //private ImageView iv_portrait;
    private Uri imageUri;// 拍照时的图片uri
    @BindView(R.id.my_ifo_zhanghao)
    TextView etZhanghao;
    @BindView(R.id.my_username)
    TextView etNiCheng2;
    @BindView(R.id.et_email)
    TextView etEmail;
    @BindView(R.id.et_phone)
    TextView etPhone;
    @BindView(R.id.iv_portrait)
    ImageView ivPortrait;
   // String path;
   // private  static final  int MY_REQUEST_CODE=0x23;
    @Override
    public int initLayout() {
        return R.layout.activity_myinformation;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);//注册butterknife（起作用）
        mReturnView=findViewById(R.id.my_ifo_return);
        mReturnView.setOnClickListener(this);
        mImageView=findViewById(R.id.turn_infor);
        mImageView.setOnClickListener(this);
        goToNicheng=findViewById(R.id.goto_nicheng);
        goToPhone=findViewById(R.id.goto_phone);
        goToEmail=findViewById(R.id.goto_email);
        goToSex=findViewById(R.id.goto_sex);
        ivSex=findViewById(R.id.iv_sex);

        goToBirthday=findViewById(R.id.goto_birthday);

        goToNicheng.setOnClickListener(this);
        goToPhone.setOnClickListener(this);
        goToEmail.setOnClickListener(this);
        goToSex.setOnClickListener(this);
        goToBirthday.setOnClickListener(this);
    }

    public void initData() {
      //Glide加载图片，load（“图片资源（url，id）”）
        Glide.with(this).load(R.mipmap.unlogin1)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))//把图片加载为圆形
                .into(ivPortrait);//加载到哪一个控件
           //User user = MyApp.getCurrentUser();
            etEmail.setText(MyApp.getCurrentUser().getEmail());
            etPhone.setText(MyApp.getCurrentUser().getPhone());
            etZhanghao.setText((MyApp.getCurrentUser().getId()).toString());
            etNiCheng2.setText(MyApp.getCurrentUser().getUsername());
           // ivPortrait.setImageBitmap(user.getHeadPortraitUrl());

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.my_ifo_return:
                finish();
                break;
            case R.id.turn_infor:
                takePhotoOrSelectPicture();// 拍照或者调用图库
                break;
            case R.id.goto_nicheng:
                goNextActivity(UpdateUserNameInfoActivity.class);
                break;
            case R.id.goto_phone:
                toastShort("点击了phone");
                break;
            case R.id.goto_email:
                toastShort("点击了email");
                break;
            case R.id.goto_sex:
                takeGoToSex();//选择性别
                break;
            case R.id.goto_birthday:
                toastShort("点击了birthday");
                break;
        }
    }

    private void  takeGoToSex(){
        final String[] items2 = {"男", "女"};
        AlertDialog.Builder alertBuilder2 = new AlertDialog.Builder(this);
        alertBuilder2.setTitle("性别");
        alertBuilder2.setSingleChoiceItems(items2, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MyInformationActivity.this, items2[i], Toast.LENGTH_SHORT).show();
            }
        });

        alertBuilder2.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if(i!=0)
                    ivSex.setText("女");
            }
        });

        alertBuilder2.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                alertDialog1.dismiss();
            }
        });

        alertDialog1 = alertBuilder2.create();
        alertDialog1.show();

        //toastShort("点击了sex");
    }
    private void takePhotoOrSelectPicture() {
        CharSequence[] items = {"拍照","图库"};// 裁剪items选项

        // 弹出对话框提示用户拍照或者是通过本地图库选择图片
        new AlertDialog.Builder(MyInformationActivity.this)
                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        switch (which){
                            // 选择了拍照
                            case 0:
                                // 创建文件保存拍照的图片
                                File takePhotoImage = new File(Environment.getExternalStorageDirectory(), "take_photo_image.jpg");
                                try {
                                    // 文件存在，删除文件
                                    if(takePhotoImage.exists()){
                                        takePhotoImage.delete();
                                    }
                                    // 根据路径名自动的创建一个新的空文件
                                    takePhotoImage.createNewFile();
                                }catch (Exception e){
                                    e.printStackTrace();
                                }
                                // 获取图片文件的uri对象
                                imageUri = Uri.fromFile(takePhotoImage);
                                // 创建Intent，用于启动手机的照相机拍照
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                // 指定输出到文件uri中
                                intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                                // 启动intent开始拍照
                                startActivityForResult(intent, TAKE_PHOTO);
                                break;
                            // 调用系统图库
                            case 1:

                                // 创建Intent，用于打开手机本地图库选择图片
                                Intent intent1 = new Intent(Intent.ACTION_PICK,
                                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                // 启动intent打开本地图库
                                startActivityForResult(intent1,LOCAL_CROP);
                                break;

                        }

                    }
                }).show();
    }






    /**
     * 调用startActivityForResult方法启动一个intent后，
     * 可以在该方法中拿到返回的数据
     */

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode){

            case TAKE_PHOTO:// 拍照

                if(resultCode == RESULT_OK){
                    // 创建intent用于裁剪图片
                    Intent intent = new Intent("com.android.camera.action.CROP");
                    // 设置数据为文件uri，类型为图片格式
                    intent.setDataAndType(imageUri,"image/*");
                    // 允许裁剪
                    intent.putExtra("scale",true);
                    // 指定输出到文件uri中
                    intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                    // 启动intent，开始裁剪
                    startActivityForResult(intent, CROP_PHOTO);
                }
                break;
            case LOCAL_CROP:// 系统图库

                if(resultCode == RESULT_OK){
                    // 创建intent用于裁剪图片
                    Intent intent1 = new Intent("com.android.camera.action.CROP");
                    // 获取图库所选图片的uri
                    Uri uri = data.getData();
                    intent1.setDataAndType(uri,"image/*");
                    //  设置裁剪图片的宽高
                    intent1.putExtra("outputX", 300);
                    intent1.putExtra("outputY", 300);
                    // 裁剪后返回数据
                    intent1.putExtra("return-data", true);
                    // 启动intent，开始裁剪
                    startActivityForResult(intent1, CROP_PHOTO);
                }

                break;
            case CROP_PHOTO:// 裁剪后展示图片
                if(resultCode == RESULT_OK){
                    try{
                        // 展示拍照后裁剪的图片
                        if(imageUri != null){
                            // 创建BitmapFactory.Options对象
                            BitmapFactory.Options option = new BitmapFactory.Options();
                            // 属性设置，用于压缩bitmap对象
                            option.inSampleSize = 2;
                            option.inPreferredConfig = Bitmap.Config.RGB_565;
                            // 根据文件流解析生成Bitmap对象
                            Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri), null, option);
                            // 展示图片
                            //ivPortrait.setImageBitmap(bitmap);
                            Glide.with(this).load(bitmap)
                                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))//把图片加载为圆形
                                    .into(ivPortrait);//加载到哪一个控件
                        }

                        // 展示图库中选择裁剪后的图片
                        if(data != null){
                            // 根据返回的data，获取Bitmap对象
                            Bitmap bitmap = data.getExtras().getParcelable("data");
                            // 展示图片
                            //ivPortrait.setImageBitmap(bitmap);
                            Glide.with(this).load(bitmap)
                                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))//把图片加载为圆形
                                    .into(ivPortrait);//加载到哪一个控件

                        }

                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                break;

        }

    }

}
